﻿using Common;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Hosting;
using Serilog;
using System;
using System.IO;

namespace Web
{
    public class Program
    {

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, builder) =>
                {
                    builder.AddEnvJsonConfig();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder
                    .UseStartup<Startup>()
                    .UseSerilog();
                });

        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                    .WriteTo.Console()
                    .CreateLogger();
            try
            {
                var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                Log.Information($"启动 Asp.Net Core {env}");
                CreateDirectory("logs");
                CreateDirectory("App_Data");
                CreateDirectory("Config");
                CreateDirectory("Config/HomeMenu");
                CreateDirectory("Config/Instrument");
                CreateDirectory("Config/Api");
                CreateHostBuilder(args).Build().Run();
                return;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
                return;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        private static void CreateDirectory(string name)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), name);
            if (Directory.Exists(path)) return;
            Directory.CreateDirectory(path);
        }
    }
}
